import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:wallpaper/themes/theme.dart';

class ThemeProvider extends ChangeNotifier {
  ThemeData _themeData = lightMode;
  bool _followSystem = false;
  bool _isInitialized = false;
  VoidCallback? _brightnessListener;

  ThemeData get themeData => _themeData;
  bool get isDarkMode => _themeData == darkMode;
  bool get followSystem => _followSystem;

  ThemeProvider() {
    _initTheme();
  }

  // 初始化主题（异步）
  Future<void> _initTheme() async {
    if (_isInitialized) return;

    final prefs = await SharedPreferences.getInstance();
    _followSystem = prefs.getBool('followSystem') ?? false;

    if (_followSystem) {
      _themeData = _getSystemTheme();
    } else {
      final isDark = prefs.getBool('isDark') ?? false;
      _themeData = isDark ? darkMode : lightMode;
    }

    _addSystemThemeListener();
    _isInitialized = true;
    notifyListeners();
  }

  // 系统主题监听
  void _addSystemThemeListener() {
    _brightnessListener = () {
      if (_followSystem) {
        _themeData = _getSystemTheme();
        notifyListeners();
      }
    };

    WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
        _brightnessListener;
  }

  // 清理资源
  @override
  void dispose() {
    WidgetsBinding.instance.platformDispatcher.onPlatformBrightnessChanged =
        null;
    super.dispose();
  }

  // 统一保存配置
  Future<void> _savePreferences() async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setBool('isDark', isDarkMode);
    await prefs.setBool('followSystem', _followSystem);
  }

  // 切换主题
  void toggleTheme() {
    _followSystem = false;
    _themeData = isDarkMode ? lightMode : darkMode;
    _savePreferences();
    notifyListeners();
  }

  // 设置浅色主题
  void setLightTheme() {
    _followSystem = false;
    _themeData = lightMode;
    _savePreferences();
    notifyListeners();
  }

  // 设置深色主题
  void setDarkTheme() {
    _followSystem = false;
    _themeData = darkMode;
    _savePreferences();
    notifyListeners();
  }

  // 跟随系统主题
  void setFollowSystem() {
    _followSystem = true;
    _themeData = _getSystemTheme();
    _savePreferences();
    notifyListeners();
  }

  // 获取系统主题
  ThemeData _getSystemTheme() {
    final brightness =
        WidgetsBinding.instance.platformDispatcher.platformBrightness;
    return brightness == Brightness.dark ? darkMode : lightMode;
  }
}
